#include <Poller/EventPoller.h>
#include "VaryFrameWriter.h"
#include <Util/util.h>
#include <Util/onceToken.h>
#include "VarySession.h"
#include "FFmpeg/impl/FFmpegEncoder.hpp"
#include <Network/TcpServer.h>
#include <Http/HttpSession.h>
#include <Common/config.h>
using namespace toolkit;
using namespace mediakit;
std::shared_ptr<VarySession> vary_session;
void initEventListener(){
    static onceToken s_token([](){
        NoticeCenter::Instance().addListener(nullptr,Broadcast::kBroadcastHttpRequest,[](BroadcastHttpRequestArgs){
            //const Parser &parser,HttpSession::HttpResponseInvoker &invoker,bool &consumed
            if(strstr(parser.Url().data(),"/api/vary") != parser.Url().data()){
                return;
            }
            if(parser.Method() != "POST"){
                return;
            }
            //url以"/api/起始，说明是http api"
            consumed = true;//该http请求已被消费
            const std::string& content = parser.Content();
            InfoL << content;
            Json::CharReaderBuilder reader_builder;
            Json::CharReader* reader = reader_builder.newCharReader();
            Json::Value val;
            std::string err;
            if(!reader->parse(content.data(), content.data() + content.size(), &val, &err)){
                HttpSession::KeyValue headerOut;
                invoker(401, headerOut, "请求参数有误");
                return;
            }

            vary_session = std::make_shared<VarySession>();
            vary_session->setExceptionHandler([invoker](const std::string& str){
                EventPollerPool::Instance().getPoller(false)->async([invoker, str](){
                    HttpSession::KeyValue headerOut;
                    invoker(500,headerOut, str);
                });
            });
            vary_session->setOnSuccess([invoker](){
                EventPollerPool::Instance().getPoller(false)->async([invoker](){
                    HttpSession::KeyValue headerOut;
                    //你可以自定义header,如果跟默认header重名，则会覆盖之
                    //默认header有:Server,Connection,Date,Content-Type,Content-Length
                    //请勿覆盖Connection、Content-Length键
                    //键名覆盖时不区分大小写
                    //headerOut["TestHeader"] = "HeaderValue";
                    invoker(200,headerOut,"success");
                });
            });
            vary_session->Excute(val);
        });

    }, nullptr);
}

int main(){

    //设置退出信号处理函数
    static semaphore sem;
    signal(SIGINT, [](int) { sem.post(); });// 设置退出信号

    //设置日志
    Logger::Instance().add(std::make_shared<ConsoleChannel>());
    Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());

    EventPollerPool pool = EventPollerPool::Instance();

    initEventListener();
    //VarySession::Ptr vary_session = std::make_shared<VarySession>();
    //开启http服务器
    TcpServer::Ptr httpSrv(new TcpServer());
    httpSrv->start<HttpSession>(8080);//默认80
    sem.wait();
    return 0;
}